# 抽取生成url的代码
import json
from urllib.parse import urlencode, parse_qs
from urllib.request import urlopen

from mall import settings


class OauthQQ(object):
    # 获取url和code
    def get_oauth_url(self, state):
        # 设置base_url,需要添加 ?
        base_url = 'https://graph.qq.com/oauth2.0/authorize?'
        # 组织参数
        params = {
            'response_type': 'code',
            'client_id': settings.QQ_APP_ID,
            'redirect_uri': settings.QQ_REDIRECT_URL,
            'state': state,
        }
        # 对参数进行urlencode,然后拼接auth_url
        auth_url = base_url + urlencode(params)
        return auth_url

    # 通过code获取token
    def get_access_token(self, code):
        # 设置base_url
        base_url = 'https://graph.qq.com/oauth2.0/token?'
        # 组织参数
        params = {
            'grant_type': 'authorization_code',
            'client_id': settings.QQ_APP_ID,
            'client_secret': settings.QQ_APP_KEY,
            'redirect_uri': settings.QQ_REDIRECT_URL,
            'code': code
        }
        # 对参数进行urlencode,然后拼接url
        url = base_url + urlencode(params)

        # 服务器向QQ服务器发送请求,获取响应
        response = urlopen(url)

        # 读取数据
        # data是由二进制数据转化成字符串
        data = response.read().decode()
        # 将字符串类型转成字典
        query_params = parse_qs(data)

        # 获取token
        access_token = query_params.get('access_token')
        # access_token是一个列表

        # 判断是否有access_token
        if access_token is None:
            raise Exception('获取token失败')

        return access_token[0]

    # 通过token获取openid
    def get_openid(self, access_token):
        # https://graph.qq.com/oauth2.0/me
        # GET
        # access_token        必须      在Step1中获取到的accesstoken。
        # 设置base_url
        base_url = 'https://graph.qq.com/oauth2.0/me?'
        # 组织参数
        params = {
            'access_token': access_token
        }
        # 拼接url
        url = base_url + urlencode(params)
        # 服务器向QQ服务器发送请求,获取响应
        response = urlopen(url)
        # 读取数据
        response_data = response.read().decode()
        # 返回数据 callback({"client_id": "YOUR_APPID", "openid": "YOUR_OPENID"})\n;
        # 转化成字典
        data = json.loads(response_data[10:-4])
        # 获取openid
        openid = data.get('openid', None)
        return openid
